package com.datastructure.test.appearmorethanhalfinarray;

import java.util.HashMap;
import java.util.Map;

public class AppearMoreThanHalfInArray {

    public static void main(String[] args) {
        AppearMoreThanHalfInArray appearMoreThanHalfInArray = new AppearMoreThanHalfInArray();
        int[] data = {3,3,3,3,2,2,2};
        int halfNumSolution = appearMoreThanHalfInArray.MoreThanHalfNum_Solution(data);
        System.out.println(halfNumSolution);
    }

    public int MoreThanHalfNum_Solution(int [] array) {
        if(array.length==1){
            return array[0];
        }
        int length=array.length/2;
        int lastValue = -1;
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            int temp = array[i];
            if(!map.containsKey(temp)){
                map.putIfAbsent(temp, 1);
            } else {
                map.computeIfPresent(temp,(key,value)-> value+1);
                Integer integer = map.get(temp);
                if(integer>length){
                    return temp;
                }
            }
        }
        return lastValue;
    }
}
